package login

import (
	"context"
	"errors"
	"go_zero_blog/common/helper"
	"go_zero_blog/common/xerr"
	"go_zero_blog/models"
	"gorm.io/gorm"

	"go_zero_blog/internal/svc"
	"go_zero_blog/internal/types"

	"github.com/zeromicro/go-zero/core/logx"
)

type RegisterLogic struct {
	logx.Logger
	ctx    context.Context
	svcCtx *svc.ServiceContext
}

func NewRegisterLogic(ctx context.Context, svcCtx *svc.ServiceContext) *RegisterLogic {
	return &RegisterLogic{
		Logger: logx.WithContext(ctx),
		ctx:    ctx,
		svcCtx: svcCtx,
	}
}

func (l *RegisterLogic) Register(req *types.RegisterReq) (resp *types.RegisterRes, err error) {
	DB := l.svcCtx.DB
	var user struct {
		Uid      uint   `json:"uid"`
		Username string `json:"username"`
		Tel      int    `json:"tel"`
	}
	if !helper.IsPhone(string(req.Tel)) {
		return nil, xerr.NewErrMsg("手机号格式错误")
	}
	//判断用户是否存在
	isExistDB := DB.Model(&models.User{}).Where("username = ? or tel = ? ", req.Username, req.Tel).First(&user)

	if err = isExistDB.Error; err != nil {
		//不存在创建用户
		if errors.Is(err, gorm.ErrRecordNotFound) {
			createDB := DB.Model(&models.User{}).Create(&models.User{
				Username:        req.Username,
				Password:        helper.SaltedMd5(req.Password, "go_zero_blog"),
				Tel:             req.Tel,
				AvatarUrl:       req.Avatar,
				BackgroundImage: req.BackgroundImage,
			}).Scan(&user)
			if err = createDB.Error; err != nil {
				return nil, xerr.NewErrCode(xerr.DBError)
			}
			return &types.RegisterRes{
				Uid: uint32(user.Uid),
			}, nil
		}
		return nil, err
	}
	if user.Username == req.Username {
		return nil, xerr.NewErrCode(xerr.UserExistError)
	}
	if user.Tel == req.Tel {
		return nil, xerr.NewErrCode(xerr.UserTelExistError)
	}
	return resp, nil
}
